<template>
  <div class="h-full w-full">
    <SplitPanel v-show="!showForm" :style="{ 'flex-direction': 'row !important' }" class="user-page-box">
      <template #left-content>
        <div class="flex justify-between flex-col h-full">
          <Tree v-model:expandedKeys="state.expandedKeys" auto-expand-parent :tree-data="state.dataTree"
            @select="onTreeSelect">
          </Tree>
        </div>
      </template>
      <template #right-content>
        <DynamicTable :formProps="formProps" auto-height show-index :data-request="loadTableData" :columns="columns"
          :closable="false">
          <template #toolbar>
            <a-button type="primary" @click="newFlow()">
              <PlusOutlined />新建流程
            </a-button>
          </template>
        </DynamicTable>
        <a-config-provider :theme="{
          algorithm: theme.defaultAlgorithm,
          token: {
            colorBgBase: '#FFF',
          },
        }">

          <a-modal v-if="addForm" @cancel="handleDrawClose" @ok="designViewInit" class="formDrawer bg-white" :closable="false"
            title="新建流程" width="50%" height v-model:open="addForm" placement="bottom" destroyOnClose>
            <a-form style="height: 30vh;" ref="flowInfoRef" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"
              :model="procInfo.procInfo">
              <a-row :gutter="24" style="margin-left: 0px;margin-right:50px;margin-top: 20px;">
                <a-col :span="24">
                  <a-form-item label="流程名称" name="name" :rules="[{ required: true, message: '请输入流程名称!' }]">
                    <a-input v-model:value="procInfo.procInfo.name"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="流程分类" name="sortId">
                    <a-tree-select v-model:value="procInfo.procInfo.sortId" placeholder="请选择"
                      :tree-data="nodeFormOptions" defaultValue="" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-modal>

        </a-config-provider>
      </template>
    </SplitPanel>
    <div v-if="showForm" @close="handleDrawClose" class="formDrawer bg-white overflow-auto p-[14px]" :closable="false" width="100%" height="90%"
       placement="bottom" :keyboard="false" destroyOnClose>
      <DesignView @closeDrawer="handleDrawClose" :xml="designXML" :taskList="taskList" :connectionList="connectionList">
      </DesignView>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import { Tree, Modal, Alert } from 'ant-design-vue';
import type { LoadDataParams, TableColumn } from '@/components/core/dynamic-table';
import { type TreeDataItem } from '@/core/permission/utils';
import { useTable } from '@/components/core/dynamic-table';
import {
  getFlowList, deleteFlow, deploymentXML, getTaskListWithProcessKey, getBusinessMethodListByProcessDefinitionId,
  getConnectionListByProcessKey, getGateWayListByProcDefKey
} from '@/api/flow/index';
import { theme } from 'ant-design-vue';
import { formatFlowSortTree } from '@/views/flow/category/columns';
import {
  DeleteOutlined,
  SettingOutlined,
  WalletOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue';
import { getFlowSortList } from '@/api/flow/sort';
import type { SchemaFormProps } from '@/components/core/schema-form';
import { flatTree } from '@/core/permission/utils';
import { cloneDeep } from 'lodash-es';
// import DesignView from '@/components/design/designView';
import { processInfo } from '@/store/modules/processInfo';
import { getFlowParamsTemplate, getTemporaryVariable, getTimeoutEntityList } from '@/api/deployment/index';
import { taskAttr } from '@/store/modules/taskAttr';
import { gateWayAttr } from '@/store/modules/gateWay';
import { businessMethods } from '@/store/modules/businessMethod';
import DesignView from "@/components/design/index.vue";
import type { FormInstance } from 'ant-design-vue';
import { getProcessProperties } from '@/api/deployment/index';

defineOptions({
  name: 'FlowList',
});
interface State {
  expandedKeys: any;
  dataTree: TreeDataItem[];
}
const searchValue = ref('');
//加载流程类别数据
const nodeFormOptions = ref<[{}]>();
const formProps = reactive<SchemaFormProps>({
  resetFunc: async () => {
    choosedSort.value = '';
  },
});
const state = reactive<State>({
  expandedKeys: "",
  dataTree: [],
});


const designXML = ref<any>(null);
const taskList = ref<any>(null);
const connectionList = ref<any>(null);
const gateWayList = ref<any>(null);
const flowInfoRef = ref<FormInstance>();

const formId = ref('');
const tabList = ref<API.FlowSortListResultItem[]>();
const activeKey = ref();
const choosedSort = ref('');
//节点列表
const taskAttrStore = taskAttr();
//网关列表
const gateWayStore = gateWayAttr();
//业务方法列表
const businessMethodsStore = businessMethods();

const showForm = ref(false);
const addForm = ref(false);
const handleDrawClose = () => {
  procInfo.setStateData("name", "");
  procInfo.setStateData("sortId", "");
  procInfo.setStateData("id", "");
  showForm.value = false;
  addForm.value = false;
  dynamicTableInstance?.reload?.();
};
const designViewInit = () => {
  console.log(procInfo.procInfo, "procInfo.procInfo11111111111111111111111")
  showForm.value = true;
};
const procInfo = processInfo();
// 获取分类数据
const loadSortList = async () => {
  procInfo.setStateData("id", "");
  const data = await getFlowSortList();
  const flatTreeData = flatTree(data.result);
  tabList.value = formatFlowSortTree(cloneDeep(flatTreeData), 0) as any;
  if (tabList.value?.length) {
    activeKey.value = tabList.value[0].sortId;

  }
  state.dataTree = formatFlowSortTree(cloneDeep(flatTreeData), 0);
  nodeFormOptions.value = transformTreeData(state.dataTree);
  console.log(state.dataTree, "11111");
};
loadSortList();
/**
   * 点击模版
   */
const onTreeSelect = (selectedKeys: number[]) => {
  state.expandedKeys = selectedKeys;
  dynamicTableInstance?.reload?.();
};

// 编辑
const handleEdit = async (row) => {
  const res = await deploymentXML({ deploymentId: row.procDefId });
  if (res) {
    designXML.value = res;
  }
  procInfo.setStateData("id", row.procDefId);
  procInfo.setStateData("name", row.procName);
  procInfo.setStateData("sortId", row.flowSort);
  const data = await getTaskListWithProcessKey({ PROCESS_KEY: row.procDefId });
  if (data.error == 200) {
    const taskInfo = data.result.map((item) => {
      if (item.TASK_RUN_DATA != "") {
        item.TASK_RUN_DATA = JSON.parse(item.TASK_RUN_DATA)
      }
      if (item.TASK_NODE_FORM_DATA_POWER != "") {
        item.TASK_NODE_FORM_DATA_POWER = JSON.parse(item.TASK_NODE_FORM_DATA_POWER)
      }
      return item;
    });
    taskList.value = taskInfo;
  }
  const proper = await getProcessProperties({ id: row.procDefId });
  if (proper.error == "200") {
    procInfo.setStateData("form_type", proper.result.form_type);
    procInfo.setStateData("form_url", proper.result.form_url);
    procInfo.setStateData("formId", proper.result.formId);
    procInfo.setStateData("picture", proper.result.picture);
    procInfo.setStateData("startPower", proper.result.startPower);
    procInfo.setStateData("titleModel", proper.result.titleModel);
    procInfo.setStateData("powerData", JSON.parse(proper.result.powerData));
  }
  //todo 需要和tasklist合并 ,要考虑是脚本的情况，目前只是一种情况
  const connectData = await getConnectionListByProcessKey({ PROCESS_KEY: row.procDefId });
  if (connectData.error == 200) {
    if (connectData.result.length === 0) {
      // const blankConnection = createConnection();
      //connectionList.value=blankConnection;
      connectionList.value = [];
    }
    else {
      const connectionsInfo = connectData.result.map((item) => {
        if (item.expressBody != "") {
          item.expressBody = JSON.parse(item.expressBody)
        }
        return item;
      });
      connectionList.value = connectionsInfo;
    }

    //
  }

  //网关
  const gateWays = await getGateWayListByProcDefKey({ PROC_DEF_ID: row.procDefId });
  if (gateWays.error == 200) {
    if (gateWays.result.length === 0) {
      gateWayList.value = [];
    }
    else {
      gateWayList.value = gateWays.result;
    }
    gateWayStore.setStateData(gateWayList);
  }
  //业务方法
  const bizMethods = await getBusinessMethodListByProcessDefinitionId({ PROC_DEF_ID: row.procDefId });
  if (bizMethods.status === '200') {
    let bizlist;
    if (bizMethods.result.length === 0) {
      bizlist = [];
    }
    else {
      bizlist = bizMethods.result;
    }
    businessMethodsStore.setStateData(bizlist);
  }


  procInfo.procVariable = [];
  const paramRes = await getFlowParamsTemplate();
  if (paramRes.status === "200") {
    const paramTree = formatFormTree(paramRes.result.filter((item => item.paramClass == "0")), "0");
    procInfo.setVariable(paramTree);
  }
  const temporaryVariableRes = await getTemporaryVariable({ PROC_DEF_ID: row.procDefId });
  if (temporaryVariableRes.status === "200") {
    procInfo.setVariable(temporaryVariableRes.result);
  }
  console.log(procInfo, "procInfo111111111111")
  const timeoutRes = await getTimeoutEntityList({ proc_def_id: row.procDefId });
  if (timeoutRes.status === "200") {
    procInfo.setStateData('timeoutData', timeoutRes.result);
  }
  if (res && data) {
    showForm.value = true;
  }
};
// 新增
const newFlow = () => {
  taskList.value = [];
  connectionList.value = [];
  businessMethodsStore.$reset();
  gateWayStore.$reset();
  procInfo.setStateData("id", "");
  procInfo.setStateData("sortId", '1');
  designXML.value = null;
  addForm.value = true;
};

const [DynamicTable, dynamicTableInstance] = useTable();

const loadTableData = async (params: LoadDataParams) => {
  const data = await getFlowList({
    ...params,
    flowSort: state.expandedKeys.length ? state.expandedKeys[0] : '',
    pageNum: params.page,
    pageSize: params.limit,
  });
  return {
    list: data.rows || [],
    pagination: {
      total: data.total,
      size: params.limit,
      page: params.page,
    },
  } as any;
};
const formatFormTree = (
  datas: [],
  parentNo: number | string = 0,
  keyPath: (string | number)[] = [],
): TreeDataItem[] => {
  return datas
    .filter((item) => item.parentId === parentNo)
    .map((item) => {
      const _keyPath = keyPath.concat(parentNo || []);
      const arr = formatFormTree(datas, item.id, _keyPath);
      return Object.assign(item, {
        title: item.name,
        key: item.id,
        label: item.name,
        value: item.id,
        children: arr.length ? arr : [],
      });
    });
};
const handledeleteFlow = async (procKey) => {
  await deleteFlow(procKey);
  dynamicTableInstance?.reload();
};

const columns: TableColumn[] = [
  {
    title: '流程名称',
    dataIndex: 'procName',
    align: 'center',
    width: 220,
  },
  {
    title: '流程分类',
    dataIndex: 'flowSortName',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '所属表单',
    dataIndex: 'formType',
    align: 'center',
    hideInSearch: true,
    customRender: ({ record }) => {
      if (record.formType === "0") {
        return "内置表单"
      }
      else if (record.formType === "1") {
        return "内置表单"
      }
      else {
        return ""
      }
    },
  },
  {
    title: '模版编码',
    dataIndex: 'procKey',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '创建人',
    dataIndex: 'CREATE_BY',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'CREATE_TIME',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '操作',
    width: 220,
    dataIndex: 'ACTION',
    align: 'center',
    actions: ({ record }) => [
      {
        label: '编辑',
        icon: h(SettingOutlined),
        onClick: () => {
          handleEdit(record);
          formId.value = record.procId;
        },
      },
      {
        label: '删除',
        danger: true,
        icon: h(DeleteOutlined),
        popConfirm: {
          title: '你确定要删除吗？',
          onConfirm: () => handledeleteFlow(record.procKey),
        },
      },
    ],
  },
];
const transformTreeData = (data: any[]): any[] => {
  return data.map(node => ({
    value: node.sortId,
    label: node.sortName,
    title: node.sortName,
    children: node.children ? transformTreeData(node.children) : undefined,
  }));
};
</script>
<style lang="less" scoped>
@import '@/styles/navTheme.less';
@classBacks: theme-tab-container-flow;
.customSetStyle(@classBacks, background-color, 'content-back');

.theme-tab-container-flow {
  margin-bottom: 10px;
  padding: 10px 0 20px 16px;
  background-color: #fff;

  .noBox {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100px;
    background: rgba(#000, 0.03);
    font-size: 14px;
  }

  .card-box {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: calc(100vw - 280px);
    overflow: auto;

    .card-content {
      display: inline-block;
      box-sizing: border-box;
      width: 226px;
      height: 100px;
      border-radius: 4px;
      color: #fff;
      font-size: 16px;
      margin-right: 10px;
      line-height: 100px;
      text-align: center;
      cursor: pointer;
      flex-shrink: 0;

      &:last-of-type {
        margin-right: 0;
      }

      &:hover,
      &.is-active {
        box-shadow:
          0 2px 7px 0 rgb(0 0 0 / 32%),
          0 1px 4px 0 rgb(183 183 183 / 6%);
      }
    }
  }
}
</style>
<style lang="less" scoped>
@import '@/styles/navTheme.less';
@classBacks: user-page-box;
.customSetStyle(@classBacks, background-color, 'content-back-user');

:deep(.ant-tree) {
  flex: 1;
}
</style>
